Passed
Push — master ( 1adf40...f067da )
by lv
01:05
created

module.exports   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 45
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 29
c 0
b 0
f 0
nc 2
dl 0
loc 45
rs 9.184
nop 2
1
const Redis = require('./libraries/redis')
2
const Constant = require('./libraries/constant')
3
const ApiError = require('./util/api_error')
4
module.exports = function (permission) {
5
6
	return async function (ctx, next) {
7
8
		async function checkToken() {
9
			let token = (typeof (ctx.request.headers.token) == 'undefined' || !ctx.request.headers.token) ?
10
				ctx.cookies.get('token') : ctx.request.headers.token
11
			let uid = (typeof (ctx.request.headers.uid) == 'undefined' || !ctx.request.headers.uid) ?
12
				ctx.cookies.get('uid') : ctx.request.headers.uid
13
14
			if (!token || !uid) {
15
				console.log('token: ' + token)
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
16
				console.log('uid: ' + uid)
17
				throw new ApiError('auth.error', 'token missing')
18
			}
19
20
			sessionKey = Constant.WECHAT_SESSION + token
0 ignored issues
show
Bug introduced by
The variable sessionKey seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.sessionKey.
Loading history...
21
			session = await Redis.get(sessionKey)
0 ignored issues
show
Bug introduced by
The variable session seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.session.
Loading history...
22
			session = JSON.parse(session)
23
			if (!session) {
24
				throw new ApiError('auth.error', 'token error')
25
			}
26
27
			if (session.uid == uid) {
28
				ctx.uid = uid
29
				return true
30
			} else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
31
				throw new ApiError('auth.error', 'no permission')
32
			}
33
			
34
		}
35
36
		async function checkUser() {
37
			await checkToken()
38
			await next()
39
		}
40
41
		// guest
42
		if (permission === 'guest') {
43
			await next()
44
		} else if (permission === 'user') {
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
45
			return await checkUser()
46
		} else {
47
			throw new ApiError('role.notExist')
48
		}
49
50
	}
51
52
}
53